package BehavioralPattern.Interpreter;

import java.util.Map;
import java.util.Stack;

/**
 * @Classname : Caculator
 * @Description : 解析器封装类
 * @Author : chentianyu
 * @Date 2023/3/10 06:49
 */


public class Caculator {
    // 定义表达式
    private Expression expression;

    // 构造函数传参并解析
    public Caculator(String expStr) {
        // 定义一个栈，安排运算先后顺序
        Stack<Expression> stack = new Stack<>();
        char[] charArray = expStr.toCharArray();
        Expression left = null;
        Expression right = null;
        for (int i=0; i < charArray.length; i++) {
            switch (charArray[i]) {
                case '+':  // 加法运算
                    left = stack.pop();
                    right = new VarExpression(String.valueOf(charArray[++i]));
                    stack.push(new AddExpression(left, right));
                    break;
                case '-':  // 减法运算
                    left = stack.pop();
                    right = new VarExpression(String.valueOf(charArray[++i]));
                    stack.push(new SubExpression(left, right));
                    break;
                default:  // 默认为公式中的变量
                    stack.push(new VarExpression(String.valueOf(charArray[i])));
            }
        }
        // 抛出运算结果
        this.expression = stack.pop();
    }

    // 开始运算
    public int run(Map<String, Integer> var) {
        return this.expression.interpret(var);
    }
}
